import socket
import threading

# 全局变量控制客户端连接状态
running = True

def receive_messages(client_socket, addr):
    """
    接收客户端消息的线程函数
    :param client_socket: 客户端的socket对象
    :param addr: 客户端的地址信息
    """
    global running
    print(f"客户端 {addr} 已连接。")
    while running:
        try:
            # 接收客户端发送的消息
            message = client_socket.recv(1024).decode('utf-8')
            if not message:
                print(f"客户端 {addr} 已断开连接。")
                break
            print(f"从客户端 {addr} 收到消息：{message}")

            # 检查是否是退出指令
            if message.lower() == "exit":
                client_socket.send("再见！".encode('utf-8'))
                running = False  # 设置全局变量触发关闭
                break
        except Exception as e:
            print(f"接收客户端 {addr} 消息时出错：{e}")
            break

    client_socket.close()
    print(f"与客户端 {addr} 的连接已关闭。")

def send_messages(client_socket, addr):
    """
    向客户端发送消息的线程函数
    :param client_socket: 客户端的socket对象
    :param addr: 客户端的地址信息
    """
    global running
    while running:
        try:
            # 等待用户输入消息
            response = input("发送消息(输入 'exit' 退出)：")
            client_socket.send(response.encode('utf-8'))

            # 检查是否是退出指令
            if response.lower() == "exit":
                running = False  # 设置全局变量触发关闭
                break
        except Exception as e:
            print(f"发送消息给客户端 {addr} 时出错：{e}")
            break

    client_socket.close()
    print(f"与客户端 {addr} 的连接已关闭。")

def handle_client(client_socket, addr):
    """
    处理客户端连接的函数
    :param client_socket: 客户端的socket对象
    :param addr: 客户端的地址信息
    """
    global running
    running = True  # 重置全局变量允许新客户端连接

    # 创建接收消息的线程
    receive_thread = threading.Thread(target=receive_messages, args=(client_socket, addr))
    receive_thread.start()

    # 创建发送消息的线程
    send_thread = threading.Thread(target=send_messages, args=(client_socket, addr))
    send_thread.start()

    # 等待两个线程结束
    receive_thread.join()
    send_thread.join()

def start_server():
    """
    启动服务器的函数
    """
    host = '0.0.0.0'  # 安卓本机的IP地址
    port = 0  # 安桌 的端口号

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((host, port))
    server_socket.listen(5)
    print("服务器正在监听连接...")

    try:
        while True:
            client_socket, addr = server_socket.accept()
            print(f"来自 {addr} 的连接已建立。")

            # 为每个客户端创建一个线程来处理消息收发
            client_handler = threading.Thread(target=handle_client, args=(client_socket, addr))
            client_handler.start()
    except KeyboardInterrupt:
        print("服务器正在关闭...")
    finally:
        server_socket.close()
        print("服务器已关闭。")

if __name__ == "__main__":
    start_server()
